"""
权限装饰器

"""
import json
from functools import wraps

from flask import g, request
from flask_login import login_required

from apps.utils.views import resp_with_data
from components.memcache.connector import cache


def authorize(power: str):
    """用户权限判断，用于判断目前会话用户是否拥有访问权限
    :param power: 权限标识
    :type power: str
    """
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            if cache.get(g.token.encode('utf-8')):
                if power not in json.loads(cache.get(g.token.encode('utf-8')))['permission']:
                    return resp_with_data(10006)
            else:
                return resp_with_data(10007)
            cache.set(g.token.encode('utf-8'), cache.get(g.token.encode('utf-8')), time=3600)
            return func(*args, **kwargs)
        return wrapper
    return decorator
